local cjson = require("cjson.safe")
local util = require("common")
local post = require('resty.post')
local drawer = require("video_bbox_drawer")
local base64 = require("base64")

local _M = {
    _VERSION = '0.0.1'
}

function _M.new( self )
    return setmetatable( {} , { __index = _M } )
end

local FILE_ROOT = "/tmp/abc/"  -- video save folder path
local post = post:new({path = FILE_ROOT} )
local res = {code = '0', message = "success", data = cjson.encode({version = 5})}

local m = post:read()

-- print(util.dump(m))
if m.stream_data then
    m.stream_data = base64.decode(m.stream_data)
    --m.stream_data = ngx.decode_base64(m.stream_data)
end
print("m.stream_data size: ", #m.stream_data)

local video_path
for k, v in pairs(m.files) do
    print(util.dump(v))
    local extension = util.getExtension(v.name)
    if extension == "h264" or extension == "mp4" or extension == "avi" then
        os.rename(FILE_ROOT .. v.tmp_name, FILE_ROOT .. v.name)
        video_path = FILE_ROOT .. v.name
        print(video_path)
        break
    end
end

local t = {
    video_file = video_path,
    outputfile = util.getfilename(video_path) .. "_".. ngx.now() * 1000 .. ".mp4",
    detect_result = m.stream_data}

print(cjson.encode({outputfile=t.outputfile}))
drawer.draw_bbox(t)
ngx.say(cjson.encode({outputfile=t.outputfile}))
